<template>
  <div class="register-container">
    <q-card class="register-card">
      <q-card-section>
        <div class="text-h6 text-center">用户注册</div>
      </q-card-section>

      <q-card-section>
        <q-form @submit="onSubmit" class="q-gutter-md">
          <q-input
            v-model="form.username"
            label="用户名"
            :rules="[
              val => !!val || '请输入用户名',
              val => val.length >= 3 || '用户名至少3个字符'
            ]"
          />

          <q-input
            v-model="form.phone"
            label="手机号"
            :rules="[
              val => !!val || '请输入手机号',
              val => /^1[3-9]\d{9}$/.test(val) || '请输入正确的手机号'
            ]"
          />

          <q-input
            v-model="form.password"
            label="密码"
            type="password"
            :rules="[
              val => !!val || '请输入密码',
              val => val.length >= 6 || '密码至少6个字符'
            ]"
          />

          <q-input
            v-model="form.confirmPassword"
            label="确认密码"
            type="password"
            :rules="[
              val => !!val || '请确认密码',
              val => val === form.password || '两次输入的密码不一致'
            ]"
          />

          <div class="row justify-between items-center">
            <q-btn
              flat
              label="返回登录"
              color="primary"
              @click="$router.push('/login')"
            />
            <q-btn
              type="submit"
              label="注册"
              color="primary"
              :loading="loading"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import { useUserStore } from '../stores/user';

const router = useRouter();
const $q = useQuasar();
const userStore = useUserStore();

const loading = ref(false);
const form = reactive({
  username: '',
  phone: '',
  password: '',
  confirmPassword: ''
});

const onSubmit = async () => {
  try {
    loading.value = true;
    await userStore.register({
      username: form.username,
      phone: form.phone,
      password: form.password
    });
    $q.notify({
      message: '注册成功，请登录',
      color: 'positive'
    });
    router.push('/login');
  } catch (error: any) {
    $q.notify({
      message: error.message || '注册失败',
      color: 'negative'
    });
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: fixed;
  top: 0;
  left: 0;
}

.register-card {
  width: 100%;
  max-width: 400px;
  margin: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style> 